<template>
    <view>
        <z-paging @pageScroll="pageScroll">
			<view class="header_box">
			    <view class="biaoti_box">
			        <view class="left_icon_box" @click="back">
			            <image src="https://www.dingxians.cn/upload/20250324/67e13c80ecef6.png" mode="scaleToFill" />
			        </view>
			        <view class="center_biaoti_box">
			            邀请海报
			        </view>
			        <view class="left_icon_box">
			            <!-- 占位 -->
			        </view>
			    </view>
			</view>
            <!-- <v-headerview actionBarColor="#000000" titleColor="#ffffff" pageTitle="邀请海报" :showBackIcon="true"> -->
                <view class="vavans_box">
                    <image :src="resultSrc" mode="scaleToFill" />
                </view>
                <view class="enter_box" @click="invitSubmit"
                    style="background-image: url('https://www.dingxians.cn/upload/20250509/681da3814f6bd.png');">保存/分享海报</view>
                <canvas v-if="!resultSrc" id="myCanvas" type="2d" class="my-canvas" />
            <!-- </v-headerview> -->
        </z-paging>
    </view>
</template>


<script>
import { downloaImage } from '../../utils/request.js';
import api from '../../api/index.js'
let ctx;
let canvas;
let timer;
export default {
    data() {
        return {
            brand: 'Tiger潮赏',
            // 用户数据
            userInfo: {
                nickName: '',
                avatarUrl: ''
            },
            qrcode: '', //太阳码
            chooseIndex: 0, //选择序列号
            cardList: [{

            }], // 海报列表
            drawList: [], // 需要画在画布上的元素
            resultSrc: '', // 最后生成的图片
            shareShow: false, //分享类型弹窗
            caozuoList: [{
                id: 1,
                icon: 'https://yq.dingxians.cn/upload/static/invited/xiazai.png',
                txt: '保存到相册'
            },
            {
                id: 2,
                icon: 'https://yq.dingxians.cn/upload/static/invited/weixin.png',
                txt: '转发给好友'
            },
            {
                id: 3,
                icon: 'https://yq.dingxians.cn/upload/static/invited/pengyouquan.png',
                txt: '分享朋友圈'
            }
            ],
            shsareImages: []
        }
    },
    onUnload() {

        if (timer) {
            clearInterval(timer);
            timer = null;
        }
    },
    onLoad(e) {
        console.log(e)

        // this.qrcode = 'https://yq.dingxians.cn/upload/static/poster1.jpg'
        // const query = uni.createSelectorQuery()
        // query.select('#my-canvas')
        // 	.fields({
        // 		node: true,
        // 		size: true
        // 	})
        // 	.exec(async (res) => {
        // 		canvas = res[0].node
        // 		ctx = canvas.getContext('2d')
        // 		const dpr = uni.getSystemInfoSync().pixelRatio
        // 		canvas.width = res[0].width * dpr // 获取宽
        // 		canvas.height = res[0].height * dpr // 获取高
        // 		ctx.scale(dpr, dpr)
        // 		ctx.textBaseline = 'top';
        // 		await this.getCardList();
        // 		this.$nextTick(() => {
        // 			this.chooseHaibao(0);
        // 		});
        // 	});
        this.getQrcodeImage()
    },
    methods: {
        // 获取太阳码
        getQrcodeImage() {
            api.share.usersGetWxCode().then(res => {
				
                if (res.code == 200) {
                    let imageSrc = res.url
                    this.shsareImages = res.img
                    this.getTempFilePath(imageSrc)
                }
            })
        },
        // 转码
        getTempFilePath(base64Data) {
            return new Promise((resolve, reject) => {
                const fs = uni.getFileSystemManager()
                base64Data = base64Data.split(',')[1]
                const fileName = 'temp_image_' + Date.now() + '.png' // 自定义文件名，可根据需要修改
                const filePath = uni.env.USER_DATA_PATH + '/' + fileName
                const buffer = uni.base64ToArrayBuffer(base64Data)
                fs.writeFile({
                    filePath,
                    data: buffer,
                    encoding: 'binary',
                    success: res => resolve(filePath),
                    fail: err => reject(err)
                })


                let userInfo = uni.getStorageSync('userInfo')
                this.userInfo.nickName = userInfo.nickname
                this.userInfo.avatarUrl = userInfo.avatar
                this.qrcode = filePath


                const query = uni.createSelectorQuery()
                query.select('#myCanvas')
                    .fields({
                        node: true,
                        size: true
                    })
                    .exec(async (res) => {
                        canvas = res[0].node
                        ctx = canvas.getContext('2d')
                        const dpr = uni.getSystemInfoSync().pixelRatio
                        canvas.width = res[0].width * dpr // 获取宽
                        canvas.height = res[0].height * dpr // 获取高
                        ctx.scale(dpr, dpr)
                        ctx.textBaseline = 'top';
                        await this.getCardList();
                        this.$nextTick(() => {
                            this.chooseHaibao(0);
                        });
                    });
                // this.$router('/userPage/invited/poster?imageSrc=' + filePath + '&image=' + JSON.stringify(image))
            });
        },


        // 打开分享操作弹窗
        invitSubmit() {
            // this.shareShow = true
            wx.downloadFile({
                url: this.resultSrc,
                success: (res) => {
                    console.log(res)
                    wx.showShareImageMenu({
                        path: res.tempFilePath
                    })
                }
            })
        },
        //关闭分享操作弹窗
        // shareclose() {
        // 	this.shareShow = false
        // },
        // 1保存、2转发、3分享操作
        // handle(item) {

        // 	if (item.id == 1) {
        // 		this.saveImage()
        // 	} else if (item.id == 2) {
        // 		this.shareImage()
        // 	} else {
        // 		this.shareToTimeline()
        // 	}
        // },
        // 转发给好友
        // shareImage() {
        // 	wx.downloadFile({
        // 	   url: this.resultSrc,
        // 	   success: (res) => {
        // 	     wx.showShareImageMenu({
        // 	       path: res.tempFilePath
        // 	     })
        // 	   }
        // 	 })
        // uni.share({
        // 	provider: "weixin",
        // 	scene: "WXSceneSession",
        // 	type: 2,
        // 	imageUrl: this.resultSrc,
        // 	success: function(res) {
        // 		console.log("success:" + JSON.stringify(res));
        // 	},
        // 	fail: function(err) {
        // 		console.log("fail:" + JSON.stringify(err));
        // 	}
        // });
        // },
        // 分享到朋友圈
        // shareToTimeline() {
        // 	let image = this.resultSrc;
        // 	uni.share({
        // 		provider: "weixin",
        // 		scene: "WXSceneSession",
        // 		type: 2,
        // 		imageUrl: image,
        // 		success: function(res) {
        // 			console.log("success:" + JSON.stringify(res));
        // 		},
        // 		fail: function(err) {
        // 			console.log("fail:" + JSON.stringify(err));
        // 		}
        // 	});

        // },

        // 获取海报列表
        getCardList() {
            this.cardList = this.shsareImages

        },

        //选择海报
        async chooseHaibao(index) {
            let self = this;
            //将图片的信息存起来,再进行跳转
            this.chooseIndex = index;
            let item = self.cardList[self.chooseIndex];
            if (item.createImg) { //如果图片已经生成过则直接使用
                var uploadurl = "https://kimi.dingxians.cn/api/common/upload?token=" + uni.getStorageSync(
                    "token")
                uni.uploadFile({
                    url: uploadurl,
                    filePath: item.createImg,
                    name: 'file',
                    success: (res) => {
                        let urlData = JSON.parse(res.data)
                        self.resultSrc = urlData.data.url;
                        uni.setStorageSync('shareresultSrc', self.resultSrc)
                    }
                });


                uni.hideLoading();
                if (timer) {
                    clearInterval(timer);
                    timer = null;
                };
                return;
            };
            this.drawList = [];
            //下载背景图片
            this.drawList.push({
                zIndex: 1,
                left: 0,
                top: 0,
                scale: 1,
                type: 'img',
                img: await downloaImage(canvas, 'https://www.dingxians.cn/upload/user_static/user/bg-inviteTop.png'),
                width: 400,
                height: 800
            });
            // 太阳码
            let qrcdoePng = this.qrcode;
            this.drawList.push({
                zIndex: 1,
                left: 240,
                top: 450,
                scale: 1,
                type: 'img',
                img: await downloaImage(canvas, qrcdoePng),
                width: 120,
                height: 120
            });
            // 用户昵称
            this.drawList.push({
                zIndex: 2,
                left: 40,
                top: 560,
                scale: 1,
                color: "#ffffff",
                fontSize: 14,
                type: 'text',
                content: this.userInfo.nickName
            });
            // this.drawList.push({
            //     zIndex: 1,
            //     left: 20,
            //     top: 190,
            //     scale: 1,
            //     type: 'img',
            //     img: await downloaImage(canvas, 'https://kimi.dingxians.cn/upload/static/invited/4.png'),
            //     width: 350,
            //     height: 30
            // });
            // 邀请你
            this.drawList.push({
                zIndex: 2,
                left: 40,
                top: 580,
                scale: 1,
                color: '#01E4FF',
                fontSize: 18,
                type: 'text',
                content: `${this.brand}邀请您`
            });
            // 说明
            // this.drawList.push({
            //     zIndex: 2,
            //     left: 90,
            //     top: 198,
            //     scale: 1,
            //     color: '#ffffff',
            //     fontSize: 15,
            //     type: 'text',
            //     content: '邀请新人15天之内得新人流水的1%'
            // });
            // 用户头像
            if (this.userInfo.avatarUrl) {
                this.drawList.push({
                    zIndex: 3,
                    left: 30,
                    top: 450,
                    scale: 1,
                    type: 'img',
                    img: await downloaImage(canvas, this.userInfo.avatarUrl),
                    width: 90,
                    height: 90
                });
            }
            uni.showLoading({
                title: '生成中...'
            });
            startDraw();
            //绘制
            function startDraw() {
                //按z-index排序
                self.drawList = self.drawList.sort((a, b) => {
                    return Number(a.zIndex) - Number(b.zIndex);
                });
                self.drawList.forEach((item) => {
                    if (item.type == 'text') {
                        self.drawText(item);
                    } else {
                        self.drawImg(item);
                    }
                });
                uni.canvasToTempFilePath({
                    destWidth: 750,
                    destHeight: 1255,
                    canvas: canvas,
                    success: (res) => {
                        uni.hideLoading();
                        ctx.clearRect(0, 0, 500, 800);
                        let tmpPath = res.tempFilePath;
                        item.createImg = tmpPath; //给元素赋值，使之第二次不需要再次生成图片
                        var uploadurl = "https://kimi.dingxians.cn/api/common/upload?token=" +
                            uni.getStorageSync("token")
                        uni.uploadFile({
                            url: uploadurl,
                            filePath: item.createImg,
                            name: 'file',
                            success: (res) => {
                                let urlData = JSON.parse(res.data)
                                self.resultSrc = urlData.data.url
                                uni.setStorageSync('shareresultSrc', self.resultSrc)
                            }
                        });

                    },
                    fail: (err) => {
                        console.log(err, 2222)
                    }
                });
            };
        },
        drawText(item) {
            if (item.content) {
                ctx.font = `${Number(item.fontSize) || 16}px 楷体`;
                ctx.fillStyle = item.color || '#333333'; ///颜色
                ctx.fillText(item.content, Number(item.left), Number(item.top));
            };
        },
        //绘制图片
        drawImg(item) {
            //由于缩放是以图片的中心点缩放的，所以会改变图像的left 和top值
            ctx.save();
            let width = Number(item.width); //初始的宽高
            let height = Number(item.height);
            item.top = Number(item.top);
            item.left = Number(item.left);
            item.scale = Number(item.scale);

            if (item.img) {
                ctx.drawImage(item.img, item.left, item.top,
                    item.width * item.scale, item.height * item.scale);
            }
            ctx.restore();
        },
        save() {
            uni.saveImageToPhotosAlbum({
                filePath: this.resultSrc,
                success: () => {
                    this.showToast('保存成功', 'success');
                }
            })
        },
        showToast(title, icon = 'none') {
            uni.showToast({
                title: title ? title.toString() : '重新登陆',
                icon
            });
        },
        //保存图片
        // saveImage() {
        // 	// 假设已有图片路径

        // 	// 先下载图片到本地
        // 	uni.downloadFile({
        // 		url: this.resultSrc,
        // 		success: downloadResult => {
        // 			if (downloadResult.statusCode === 200) {
        // 				// 获取下载后的图片临时文件路径
        // 				let tempFilePath = downloadResult.tempFilePath;

        // 				// 保存图片到相册
        // 				uni.saveImageToPhotosAlbum({
        // 					filePath: tempFilePath,
        // 					success: () => {
        // 						uni.showToast({
        // 							title: '保存成功'
        // 						});
        // 					},
        // 					fail: () => {
        // 						uni.showToast({
        // 							title: '保存失败',
        // 							icon: 'none'
        // 						});
        // 					}
        // 				});
        // 			}
        // 		},
        // 		fail: (err) => {
        // 			console.log(err, "下载失败")
        // 			uni.showToast({
        // 				title: '下载失败',
        // 				icon: 'none'
        // 			});
        // 		}
        // 	});
        // }
    }
}

</script>

<style lang="scss" scoped>
::v-deep.zp-scroll-view-absolute {
    background-image: none !important;
    background-color: #000 !important;
}

.header_box {
    width: 750rpx;
    height: 180rpx;
    box-sizing: border-box;
    padding-top: 92rpx;

    .biaoti_box {
        width: 100%;
        height: 88rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 20rpx;

        .left_icon_box {
            width: 80rpx;
            height: 80rpx;

            image {
                width: 100%;
                height: 100%;
            }
        }

        .center_biaoti_box {
            width: 380rpx;
            height: 88rpx;
            line-height: 88rpx;
            text-align: center;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            font-size: 40rpx;
            color: #fff;
            font-weight: 900;
        }
    }
}
.vavans_box {
    width: 750rpx;
    height: 1255rpx;

    image {
        width: 100%;
        height: 100%;
    }
}

.my-canvas {
    width: 750rpx;
    height: 1255rpx;
}

.enter_box {
    position: fixed;
    left: 0;
    right: 0;
    margin: auto;
    bottom: 160rpx;
    background-size: 100% 100%;
    text-align: center;
    width: 322rpx;
    height: 94rpx;
    line-height: 88rpx;
    font-family: Source Han Serif CN;
    font-weight: bold;
    font-size: 40rpx;
    color: #FFFFFF;
}
</style>